<template>
	<view class="publish-container">

		<view class="content">
			<view class="input-section">
				<textarea class="text-input" placeholder="编辑分享文案" v-model="content" maxlength="500"></textarea>
			</view>

			<!-- 媒体上传区域 -->
			<view class="media-section">
				<view class="media-item" v-for="(item, index) in mediaList" :key="index">
					<template v-if="item.type === 'image'">
						<image :src="item.url" mode="aspectFill" class="media-img"></image>
					</template>
					<template v-else>
						<video :src="item.url" mode="aspectFill" class="media-video"></video>
						<view class="duration-label">{{ formatDuration(item.duration) }}</view>
					</template>
					<view class="delete-btn" @click="removeMedia(index)">×</view>
				</view>
				<view class="add-media-btn" v-if="mediaList.length < 9" @click="chooseMedia">
					<text class="add-icon">+</text>
				</view>
			</view>
		</view>

		<!-- 确认发布按钮 -->
		<view class="publish-section">
			<view class="publish-btn" @click="handlePublish">确认发布</view>
		</view>
	</view>
</template>

<script>
import { uploadFile } from '@/utils/request';
import { getFullImageUrl, initBaseUrl, request } from '../../../utils/request';

export default {
	data() {
		return {
			content: '',
			mediaList: [],
			syncToCenter: false,
			feeAmount: '',
			// 上传所有媒体文件
			mediaUrls: [],
		};
	},
	methods: {
		navigateBack() {
			uni.navigateBack();
		},
		
		// 页面显示时清除发布成功标记
		onShow() {
			// 清除发布成功标记，确保下次发布时能正常显示弹窗
			uni.removeStorageSync('release_success_shown');
		},
		chooseMedia() {
			uni.chooseMedia({
				count: 9 - this.mediaList.length,
				mediaType: ['image', 'video'],
				sourceType: ['album', 'camera'],
				maxDuration: 60,
				success: (res) => {
					const tempFiles = res.tempFiles;
					tempFiles.forEach((file) => {
						// 确定媒体类型
						let mediaType = file.mediaType;
						if (!mediaType) {
							// 回退方案：通过文件扩展名判断类型
							const ext = file.tempFilePath.split('.').pop().toLowerCase();
							const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
							mediaType = imageExts.includes(ext) ? 'image' : 'video';
						}
						// 限制视频时长
						if (mediaType === 'video' && file.duration > 60) {
							uni.showToast({
								title: '视频时长不能超过60秒',
								icon: 'none',
							});
							return;
						}
						this.mediaList.push({
							url: file.tempFilePath,
							type: mediaType,
							duration: file.duration || 0,
						});
					});
				},
			});
			console.log("选择的媒体", this.mediaList);
		},
		removeMedia(index) {
			this.mediaList.splice(index, 1);
		},
		formatDuration(seconds) {
			const mins = Math.floor(seconds / 60);
			const secs = Math.floor(seconds % 60);
			return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
		},
		setFree() {
			this.feeAmount = '';
		},
		async handlePublish() {
			// 检查用户是否已登录
			const token = uni.getStorageSync('token');
			if (!token) {
				uni.showToast({ title: '请先登录', icon: 'none' });
				uni.navigateTo({ url: '/pages/pageLogin/index' });
				return;
			}
			
			if (!this.content.trim() && this.mediaList.length === 0) {
				uni.showToast({
					title: '请输入文案或上传媒体',
					icon: 'none',
				});
				return;
			}

			try {
				uni.showLoading({ title: '发布中...' });


				for (let i = 0; i < this.mediaList.length; i++) {
					const item = this.mediaList[i];
					// 上传文件
					const uploadRes = await uploadFile({
						url: '/Common/uploadLocalOnly',
						filePath: item.url,
						name: 'file'
					});
					console.log("上传结果", uploadRes);
					// 解析上传结果
					const result = JSON.parse(uploadRes);
					if (result.code !== 1) {
						throw new Error(`媒体${i + 1}上传失败: ${result.msg || '未知错误'}`);
					}

					// 保存服务器返回的路径和类型
					this.mediaUrls.push({
						url: result.data.fullurl,
						type: item.type
					});
				}
				// 提取媒体URL和类型
				const mediaUrls = this.mediaUrls.map(item => item.url);
				const mediaTypes = this.mediaUrls.map(item => item.type);

				// 调用发布接口
				const publishRes = await request({
					url: 'discover/Post/create',
					method: 'POST',
					data: {
						content: this.content,
						media_urls: mediaUrls,
						media_types: mediaTypes
					}
				});
				console.log("发布结果", publishRes);

				if (publishRes.code !== 1) {
					throw new Error(publishRes.msg || '发布失败');
				}

				// 发布成功，直接跳转
				setTimeout(() => {
					uni.reLaunch({ url: '/pages/discover/index?from=release_success' });
				}, 1000);
			} catch (error) {
				console.error('发布失败:', error);
				uni.showToast({
					title: '发布失败: ' + error.message,
					icon: 'none',
				});
			} finally {
				uni.hideLoading();
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.publish-container {
	padding: 20rpx 0;
	background-color: #F2F3F8;
	min-height: 100vh;

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		background-color: #fff;
		padding: 0 20rpx;
		border-bottom: 1rpx solid #eee;

		.back-btn,
		.menu-btn {
			width: 80rpx;
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.back-icon,
			.menu-icon {
				font-size: 32rpx;
				color: #000;
			}
		}

		.title {
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	.content {
		margin-top: 20rpx;
		background-color: #fff;
		padding: 31rpx 26rpx;

		.input-section {
			margin-bottom: 66rpx;

			.text-input {
				width: 100%;
				height: 212rpx;
				font-family: Source Han Sans CN;
				font-weight: 500;
				font-size: 30rpx;
				color: #0E1C37;
				line-height: 30rpx;
			}

			.text-input::placeholder {
				font-family: Source Han Sans CN;
				font-weight: 400;
				font-size: 30rpx;
				color: #A2A6B7;
				line-height: 26rpx;
			}
		}

		.media-section {

			background-color: #fff;
			// padding: 20rpx;

			display: flex;
			flex-wrap: wrap;

			.media-item {
				width: 160rpx;
				height: 160rpx;
				margin-right: 20rpx;
				margin-bottom: 20rpx;
				position: relative;
				overflow: hidden;
				border-radius: 8rpx;

				.media-img,
				.media-video {
					width: 100%;
					height: 100%;
				}

				.duration-label {
					position: absolute;
					bottom: 10rpx;
					left: 10rpx;
					background-color: rgba(0, 0, 0, 0.5);
					font-family: Source Han Sans CN;
					font-weight: 500;
					font-size: 22rpx;
					color: #FFFFFF;
					padding: 7rpx 11rpx 5rpx 10rpx;
					border-radius: 10rpx;
				}

				.delete-btn {
					position: absolute;
					top: 0rpx;
					right: 0rpx;
					width: 42rpx;
					height: 42rpx;
					background-color: rgba(0, 0, 0, 0.5);
					color: #fff;
					border-top-right-radius: 16rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24rpx;
				}
			}

			.add-media-btn {
				width: 160rpx;
				height: 160rpx;
				background: #EEF2F3;
				border-radius: 16rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.add-icon {
					font-size: 60rpx;
					color: #ccc;
				}
			}
		}
	}

	.sync-section {
		margin-top: 20rpx;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.sync-label {
			font-size: 28rpx;
		}

		.sync-switch {
			transform: scale(0.8);
		}
	}

	.fee-section {
		margin-top: 20rpx;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;

		.fee-label {
			font-size: 28rpx;
			margin-right: 20rpx;
		}

		.fee-input {
			flex: 1;
			height: 60rpx;
			border: 1rpx solid #ccc;
			border-radius: 8rpx;
			padding: 0 10rpx;
			font-size: 28rpx;
		}

		.free-btn {
			margin-left: 20rpx;
			font-size: 28rpx;
			color: #007AFF;
		}
	}

	.publish-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 40rpx 20rpx;
		background: #FFFFFF;

		.publish-btn {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 83rpx;
			font-family: Source Han Sans CN;
			font-weight: 500;
			font-size: 32rpx;
			color: #0E1C37;
			background: #BEFF33;
			border-radius: 12rpx;
		}
	}
}
</style>